import set from 'lodash/set';
import { gqcPermissionCheck } from '@kuiper/auth';
import escapeRegExp from '../helpers/escapeRegExp';

export default server => {
	const {
		app: {
			model: { NotificationSendLog },
			schema: { Task, User },
		},
	} = server;

	server.methods.registerGraphQLSchema({
		name: 'NotificationSendLog',
		model: NotificationSendLog,
		queryFields: {
			Count: 'count',
			Pagination: 'pagination',
		},
		mutationFields: {},
		onPreAddFields(tc) {
			const graphqlResolvers = server.app.graphqlResolvers;

			tc.addRelation('task', {
				resolver: () => Task.mongooseResolvers.dataLoader({ lean: true }),
				prepareArgs: {
					_id: source => source.taskId || [],
				},
				projection: { taskId: 1 },
			});
			tc.addRelation('user', {
				resolver: () => User.mongooseResolvers.dataLoader({ lean: true }),
				prepareArgs: {
					_id: source => source.uid || [],
				},
				projection: { uid: 1 },
			});

			// #region count
			graphqlResolvers.Query.NotificationSendLogCount = graphqlResolvers.Query.NotificationSendLogCount.addFilterArg(
				{
					name: 'startTimeGTE',
					type: 'Date',
					description: '开始时间大于等于',
					query: (query, value) => {
						const fieldName = 'startTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $gte: value };
					},
				}
			)
				.addFilterArg({
					name: 'startTimeLTE',
					type: 'Date',
					description: '开始时间小于等于',
					query: (query, value) => {
						const fieldName = 'startTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $lte: value };
					},
				})
				.addFilterArg({
					name: 'endTimeGTE',
					type: 'Date',
					description: '结束时间大于等于',
					query: (query, value) => {
						const fieldName = 'endTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $gte: value };
					},
				})
				.addFilterArg({
					name: 'endTimeLTE',
					type: 'Date',
					description: '结束时间小于等于',
					query: (query, value) => {
						const fieldName = 'endTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $lte: value };
					},
				})
				.addFilterArg({
					name: 'usernameSearch',
					type: 'String',
					description: '用户名搜索',
					query: server.methods.usernameSearchFilterArgQuery,
				})
				.addFilterArg({
					name: 'targetSearch',
					type: 'String',
					description: 'target搜索',
					query: (query, value) => {
						query.target = {
							$regex: escapeRegExp(value.trim()),
							$options: 'i',
						};
					},
				})
				.withMiddlewares([
					gqcPermissionCheck({
						required: 'cloud-monitor\x01listNotificationSendLog',
						selfOnlyArgsBuilder(
							_source,
							args,
							{
								request: {
									auth: {
										credentials: { uid },
									},
								},
							}
						) {
							set(args, ['filter', 'uid'], uid);
						},
					}),
				]);
			// #endregion

			// #region pagination
			graphqlResolvers.Query.NotificationSendLogPagination = graphqlResolvers.Query.NotificationSendLogPagination.addFilterArg(
				{
					name: 'startTimeGTE',
					type: 'Date',
					description: '开始时间大于等于',
					query: (query, value) => {
						const fieldName = 'startTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $gte: value };
					},
				}
			)
				.addFilterArg({
					name: 'startTimeLTE',
					type: 'Date',
					description: '开始时间小于等于',
					query: (query, value) => {
						const fieldName = 'startTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $lte: value };
					},
				})
				.addFilterArg({
					name: 'endTimeGTE',
					type: 'Date',
					description: '结束时间大于等于',
					query: (query, value) => {
						const fieldName = 'endTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $gte: value };
					},
				})
				.addFilterArg({
					name: 'endTimeLTE',
					type: 'Date',
					description: '结束时间小于等于',
					query: (query, value) => {
						const fieldName = 'endTime';
						let field = query[fieldName] || {};
						if (typeof field !== 'object') field = {};
						query[fieldName] = { ...field, $lte: value };
					},
				})
				.addFilterArg({
					name: 'usernameSearch',
					type: 'String',
					description: '用户名搜索',
					query: server.methods.usernameSearchFilterArgQuery,
				})
				.addFilterArg({
					name: 'targetSearch',
					type: 'String',
					description: 'target搜索',
					query: (query, value) => {
						query.target = {
							$regex: escapeRegExp(value.trim()),
							$options: 'i',
						};
					},
				})
				.withMiddlewares([
					gqcPermissionCheck({
						required: 'cloud-monitor\x01listNotificationSendLog',
						selfOnlyArgsBuilder(
							_source,
							args,
							{
								request: {
									auth: {
										credentials: { uid },
									},
								},
							}
						) {
							set(args, ['filter', 'uid'], uid);
						},
					}),
					async (resolve, source, args, context, info) => {
						const {
							request: { log },
						} = context;

						return resolve(source, args, context, info).catch(error => {
							log.error({ error, record: args.record }, error.message);
							return {
								count: 0,
								pageInfo: {
									currentPage: 0,
									perPage: 0,
									pageCount: 0,
									itemCount: 0,
									hasNextPage: false,
									hasPreviousPage: false,
								},
								items: [],
							};
						});
					},
				]);
			// #endregion
		},
	});
};
